/*
 * Created on Oct 13, 2005 6:43:18 AM
 * 
 * $Id: MemoryReadableByteStream.java,v 1.1 2005/10/16 14:15:04 olu Exp $
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package tripleo.framework.io;

import java.nio.ByteBuffer;

public class MemoryReadableByteStream implements ReadableByteStream {

	private ByteBuffer backing;
	private int mStartAvail;
	private int mRead;

	public MemoryReadableByteStream(ByteBuffer aBacking) {
		backing = aBacking;
		mStartAvail = aBacking.capacity()-aBacking.position(); 
		mRead = 0;
	}

	public long available() {
		return mStartAvail-mRead;
	}

	public byte read() {
		++mRead;
		return backing.get();
	}

	public void readInto(long aLen, WritableByteStream aTarget) {
		long goingTo = Math.min(aTarget.available(), aLen);
		mRead += goingTo;
		//
		final int iSize = (int) goingTo; // TODO: info loss
		//
//		ByteBuffer wbb = ByteBuffer.allocateDirect(iSize);
		ByteBuffer wbb = backing.duplicate();
		wbb.limit(iSize);
		aTarget.write(new MemoryReadableByteStream(wbb));
	}

	public byte[] array() {
		return backing.array();
	}

}

